import { Button, Card, Checkbox, Descriptions, Empty, Form, Input, Menu, Modal, Select, Switch, Table } from "antd"
import React, { useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
import type { MenuProps } from 'antd'
import type { ColumnsType } from 'antd/es/table';
import { typeList } from '@/assets/data'
export interface MenuItems {
    label: React.ReactNode; key: string
}
export interface AttributeCPProps {
    detailData: GetDBListDetail.Response
}
const AttributeCP: React.FC<AttributeCPProps> = (props) => {
    const { detailData } = props
    const [menusItemKey, setmenusItemKey] = useState('')
    const [confirmLoading, setconfirmLoading] = useState(false)
    const AEattributeModalRef = useRef<AEattributeModalRef>(null)
    const menuItems = useMemo<MenuItems[]>(() => {
        return detailData.attribute?.map(e => ({
            label: (<header style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>{e.description}</span>
                <span>{e.name}</span>
            </header>),
            key: e.attribute_uId
        })) ?? []
    }, [detailData])
    const detailDesc = useMemo<GetDBListPage.DBListItemAttribute | null>(() => {
        const index = detailData.attribute?.findIndex(e => e.attribute_uId === menusItemKey)
        return (index !== undefined && index !== -1) ? detailData.attribute![index] : null
    }, [menusItemKey, detailData])
    const afterModalConfirm = () => {

    }
    const columns: ColumnsType<GetDBListPage.DBListItemAttribute> = [
        {
            title: '属性名称',
            dataIndex: 'name',
            key: 'name',
            render: (_, props) => <a onClick={() => setmenusItemKey(props.attribute_uId)}>{props.name}</a>,
        },
        {
            title: '数据基本类型',
            dataIndex: 'type',
            key: 'type',
        },
        {
            title: '数据规范',
            dataIndex: 'schema',
            key: 'schema',
        },
        {
            title: '是否具有唯一性',
            dataIndex: 'unique',
            key: 'unique',
        },
        {
            title: '是否只读',
            dataIndex: 'readOnly',
            key: 'readOnly',
        }
    ];
    const openAEattributeModal = () => {
        AEattributeModalRef.current?.openModal('编辑')
    }
    useEffect(() => {
    }, [])
    // 点击菜单按钮属性
    const menuClick: MenuProps['onClick'] = (val) => setmenusItemKey(val.key)
    return (<>
        <div style={{ display: 'flex', height: '100%' }}>
            <aside style={{ border: '1px solid #f0f0f0', flexGrow: '1', overflow: 'auto', height: '65vh' }}>
                {
                    menuItems.length == 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='无内容'></Empty> : <Menu items={menuItems} onClick={menuClick} />
                }
            </aside>
            <main style={{ flexGrow: '20' }}>
                <Button type="primary" style={{ margin: '10px' }} onClick={openAEattributeModal}>新建</Button>
                <Card style={{ margin: '10px' }}>
                    {menusItemKey === '' ? <Table rowKey='attribute_uId' columns={columns} dataSource={detailData.attribute} /> :
                        <Descriptions title={detailDesc?.description} bordered>
                            <Descriptions.Item label="属性名称">{detailDesc?.name}</Descriptions.Item>
                            <Descriptions.Item label="基本类型">{detailDesc?.type}</Descriptions.Item>
                            <Descriptions.Item label="数据规范">{detailDesc?.schema}</Descriptions.Item>
                            <Descriptions.Item label="是否具有唯一性">{detailDesc?.unique}</Descriptions.Item>
                            <Descriptions.Item label="是否只读" span={2}>{detailDesc?.readOnly}</Descriptions.Item>
                        </Descriptions>}
                </Card>
            </main>
        </div>
        <AEattributeModal ref={AEattributeModalRef} afterModalConfirm={afterModalConfirm} confirmLoading={confirmLoading}></AEattributeModal>
    </>)
}


export interface AEattributeModalPrpos {
    afterModalConfirm: (formData: any, titleModal: string) => void
    confirmLoading: boolean
}
export interface AEattributeModalRef {
    openModal: (title: string, Id?: string) => void
    closeModal: () => void
}
// 新建/编辑 对话框 表单
const AEattributeModal = React.forwardRef<AEattributeModalRef, AEattributeModalPrpos>((props, ref) => {
    // 关闭对话框回调、确认按钮Loading
    const { afterModalConfirm, confirmLoading } = props
    // 控制modal打开
    const [isModalOpen, setisModalOpen] = useState(false)
    // modal表头
    const [titleModal, settitleModal] = useState('')
    // 编辑时传入Id
    const [Id, setId] = useState<string>()
    // 表单默认值
    const defaultFormData: AddRootAttribute.Request = {
        name: "",
        readOnly: false,
        schema: "",
        type: "",
        uId: "",
        unique: false
    }
    const [formData, setformData] = useState<AddRootAttribute.Request>(defaultFormData)
    const schemaOptions = useMemo<{ label: string; value: string }[]>(() => {
        const index = typeList.findIndex(e => e.value === formData.schema)
        return typeList[index].children.map(e => ({ label: e.name, value: e.value }))
    }, [formData.schema])
    // 表单ref
    const [form] = Form.useForm();
    // 确认关闭传入回调
    const handleOk = () => {
        form
            .validateFields()
            .then(values => {
                afterModalConfirm({ Id, ...Object.assign(formData, values) }, titleModal);
            })
            .catch(info => {
                console.log('Validate Failed:', info);
            });
    }
    // 关闭对话框
    const closeModal = () => {
        form.resetFields();
        setisModalOpen(false)
    }
    const onChange = () => {

    }
    // 打开对话框
    const openModal: AEattributeModalRef['openModal'] = async (title, Id) => {
        settitleModal(title)
        setId(Id)
        if (Id && Id !== '') {
            setisModalOpen(true)
        } else {
            setisModalOpen(true)
        }
    }
    // 向外暴露方法
    useImperativeHandle(ref, () => ({
        openModal,
        closeModal,
    }))
    return (<>
        <Modal confirmLoading={confirmLoading} title={titleModal} open={isModalOpen} okText='提交' cancelText='取消' onOk={handleOk} onCancel={closeModal}>
            <Form
                name="basic"
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                form={form}
            >
                <Form.Item
                    label="属性名"
                    name="name"
                    rules={[{ required: true, message: '请输入属性名（英文）!', pattern: /^[a-zA-Z]+$/ }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="是否唯一"
                    name="unique"
                >
                    <Switch checked={formData.unique} onChange={(checked) => {
                        setformData((val) => {
                            return Object.assign({}, { ...val, unique: checked })
                        })
                    }} />
                </Form.Item>

                <Form.Item
                    label="基本类型"
                    name="type"
                >
                    <Select>
                        {
                            typeList.map(e => <Select.Option key={e.value} value={e.value}>{e.name}</Select.Option>)
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label="数据规范"
                    name="schema"
                >
                    <Input />
                </Form.Item>
                <Checkbox.Group options={schemaOptions} onChange={onChange} />
                <Form.Item
                    label="是否只读"
                    name="readOnly"
                >
                    <Switch checked={formData.readOnly} onChange={(checked) => {
                        setformData((val) => {
                            return Object.assign({}, { ...val, readOnly: checked })
                        })
                    }} />
                </Form.Item>
                <Form.Item
                    label="属性描述"
                    name="description"
                >
                    <Input.TextArea rows={4} />
                </Form.Item>
            </Form>
        </Modal>
    </>)
})
export default AttributeCP